package com.tf_cut.admin.config.security;

import com.alibaba.fastjson.JSONObject;
import com.tf_cut.admin.common.pojo.Result;
import com.tf_cut.admin.util.CacheUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class WebchatAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //过滤url
        String url = request.getRequestURI();
        if(url.indexOf("/backend/agent/mobile/getVerifyCodeImage")!=-1||url.indexOf("/backend/agent/mobile/login")!=-1
        ||url.indexOf("/backend/seller/mobile/register")!=-1||url.indexOf("/backend/person/mobile/register")!=-1||url.indexOf("/backend/dict")!=-1||url.indexOf("/backend/agent/mobile/getSmsCode")!=-1){
            return true;
        }

        String token = request.getParameter("token");
        if(StringUtils.isNoneBlank(token)){
            if(StringUtils.isNoneBlank(CacheUtil.get(token))) {
                return true;
            }
        }


        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(JSONObject.toJSONString(Result.of(null, false, "token错误")));
        out.flush();
        out.close();

        return false;
    }
}
